package com.is2.patchinglife.activity;

import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;

import com.is2.patchinglife.R;
import com.is2.patchinglife.manager.ActivityManager;
import com.is2.patchinglife.manager.FacebookManager;
import com.is2.patchinglife.manager.ImageManager;
import com.is2.patchinglife.manager.LocalDataManager;
import com.is2.patchinglife.manager.RemoteDataManager;

public class ProfileActivity extends Activity {

	/** START FB **/
	private UiLifecycleHelper uiHelper;
	private Session.StatusCallback uiCallback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};
	/** END FB **/

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);

		// add activity to ActivityManager
		ActivityManager.getInstance().addActivity("ProfileActivity", this);

		/** START FB **/
		uiHelper = new UiLifecycleHelper(this, uiCallback);
		uiHelper.onCreate(savedInstanceState);
		/** END FB **/
		
		// guest user
		if(LocalDataManager.getUser().compareTo("GUEST")==0){
			
			// load guest layout
			setContentView(R.layout.activity_guest);

			// setting authentication button
			FrameLayout auth = (FrameLayout) findViewById(R.id.profileAuthBtn);
			auth.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					ActivityManager.executeButtonEffects();		// execute button effects
					
					// open login activity
					Intent main_intent = new Intent(ProfileActivity.this,LoginActivity.class);
					ProfileActivity.this.startActivity(main_intent);
					ProfileActivity.this.finish();	
				}
			});

		// authenticated user 
		}else{
			// load authenticated user layout
			setContentView(R.layout.activity_profile);

			// setting username
			TextView userText = (TextView) this.findViewById(R.id.profileUsername);
			userText.setText(LocalDataManager.getUser());

			// setting logout button
			FrameLayout Logout = (FrameLayout) findViewById(R.id.logoutBtn);
			Logout.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					ActivityManager.executeButtonEffects();		// execute button effects
					
					// reset user image
					ImageView imageView = (ImageView)findViewById(R.id.image);
					ImageManager.selectDefaultImage(imageView, getApplicationContext());
					
					RemoteDataManager.userLogout();	// logout
				}
			});
			
			// set facebook link button
			ImageView loginViewChain = (ImageView)findViewById(R.id.profileFBConn);
			loginViewChain.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					
					ActivityManager.executeButtonEffects();		// execute button effects
					
					if(Session.getActiveSession().isOpened()){
						EditText txt = (EditText)findViewById(R.id.profileTxtFacebook);
						txt.setText("");
						
						// setting button [unlink]
						FacebookManager.logoutWithRequest(ProfileActivity.this);
						
						// loginViewChain.setImageResource(R.drawable.unlink);		// change button icon
						
						
					// not yet linked
					}else{
						
						EditText txt = (EditText)findViewById(R.id.profileTxtFacebook);
						txt.setText("");
						
						// setting button [link]
						FacebookManager.loginFacebook(ProfileActivity.this, null, Arrays.asList("email"));
					
						// loginViewChain.setImageResource(R.drawable.link);	// change button icon

					}	
				}
			});
			
			// set GooglePlus link button
			ImageView loginGooglePlus = (ImageView)findViewById(R.id.profileGpConn);
			loginGooglePlus.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					
					ActivityManager.executeButtonEffects();		// execute button effects
					ActivityManager.comingSoonDialog(ProfileActivity.this);
					
				}
			});
			
			// set GooglePlus link button
			ImageView loginTwitter = (ImageView)findViewById(R.id.profileTwConn);
			loginTwitter.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					
					ActivityManager.executeButtonEffects();		// execute button effects
					ActivityManager.comingSoonDialog(ProfileActivity.this);
					
				}
			});
			
			
			
			
			/** START FB **/
			FacebookManager.initFacebookSession();
			Session session = Session.getActiveSession();
			if (session != null && (session.isOpened() || session.isClosed())) {
				onSessionStateChange(session, session.getState(), null);
			}
			/** END FB **/
		}

		// setting user image
		ImageView imageView = (ImageView)findViewById(R.id.image);
		ImageManager.loadStoredImage(imageView, getApplicationContext());
		imageView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ActivityManager.executeButtonEffects();		// execute button effects
				askImage((ImageView)v);
			}
		});
		
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		//change image
		ImageManager.setProfileImage(getApplicationContext(), requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}


	@Override
	public void onResume(){
		super.onResume();

		// loading score
		LocalDataManager.updateScore();
		String rank = LocalDataManager.getRank();
		int score = LocalDataManager.getScore();
		int trNum = LocalDataManager.getTrNum();

		// setting score
		if(LocalDataManager.getUser().compareTo("GUEST")==0){
			TextView rankText = (TextView) this.findViewById(R.id.profileGuestRank);
			rankText.setText(rank);

			TextView scoreText = (TextView) this.findViewById(R.id.profileGuestScore);
			scoreText.setText(String.valueOf(score));

			TextView trText = (TextView) this.findViewById(R.id.profileGuestTrophies);
			trText.setText(String.valueOf(trNum));
		}else{
			TextView rankText = (TextView) this.findViewById(R.id.profileRank);
			rankText.setText(rank);

			TextView scoreText = (TextView) this.findViewById(R.id.profileScore);
			scoreText.setText(String.valueOf(score));

			TextView trText = (TextView) this.findViewById(R.id.profileTrophies);
			trText.setText(String.valueOf(trNum));
		}

		ImageView imageView = (ImageView)findViewById(R.id.image);
		ImageManager.loadStoredImage(imageView, getApplicationContext());

		uiHelper.onResume();
		Session session = Session.getActiveSession();
		if (session != null ) {
			onSessionStateChange(session, session.getState(), null);
		}
	}

	
	@Override
	public void onPause() {
		super.onPause();
		/** START FB **/
		uiHelper.onPause();
		/** END FB **/
	}
	
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		/** START FB **/
		uiHelper.onSaveInstanceState(outState);
		/** END FB **/
	}

	
	@Override
	public void onDestroy(){
		String[] aList = {"ProfileActivity"};
		ActivityManager.getInstance().closeActivities(aList,false);
		super.onDestroy();
	}
	
	
	
	/** :::::::::: SUPPORT METHODS :::::::::: **/
	
	/** Allows user image selection **/
	public void askImage(final ImageView _imgView){
	
		// building alert [from layout]
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("CHANGE IMAGE");
		builder.setMessage("Select image from:");
		LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.select_image_menu, null);
		builder.setView(view);
		builder.setCancelable(true);
		final AlertDialog alert = builder.create();

		// setting image_from_gallery button
		Button btn = (Button)view.findViewById(R.id.btn_image_from_gallery);
		btn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				ImageManager.selectGalleryImage(ProfileActivity.this, _imgView);
				alert.dismiss();
			}
		});

		// setting image_from_default button
		btn = (Button)view.findViewById(R.id.btn_image_from_default);
		btn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				ImageManager.selectDefaultImage(_imgView, ProfileActivity.this.getApplicationContext());
				alert.dismiss();
			}
		});
		
		/** START FB **/
		// setting image_from_facebook button
		btn = (Button)view.findViewById(R.id.btn_image_from_fb);
		btn.setOnClickListener(new OnClickListener(){
			@Override
			
			public void onClick(View v) {
				if(Session.getActiveSession().isOpened()){
					ImageManager.selectFBimage(_imgView);
				}else{
					ImageManager.askLoginDialog(ProfileActivity.this);
				}
				alert.dismiss();
			}
		});
		/** END FB **/
		
		// button is enabled only with authenticated user
		if(LocalDataManager.getUser().compareTo("GUEST")==0){
			btn.setEnabled(false);
		}else{
			btn.setEnabled(true);
		}

		alert.show();
	}
	
	
	/** START FB **/
	/** Sets facebook textboxs in case of session change **/
	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		
		if(LocalDataManager.getUser().compareTo("GUEST")!=0){			// only with authenticated user
			if(session.isOpened()){
				EditText txt = (EditText)findViewById(R.id.profileTxtFacebook);
				txt.setText(FacebookManager.fbEmail);
			}else{
				EditText txt = (EditText)findViewById(R.id.profileTxtFacebook);
				txt.setText("");
			}

		}

	}

}